﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.Collections;
using System.IO;


namespace InfoPathTranslate
{
    class InfoPathView
    {
        private XmlDocument xd = null;
        private Hashtable actions = null;
        private XmlDocument html = null;

        public bool Translate(String path, InfoPathData data, String outputDir) 
        {
            xd = new XmlDocument();
            html = new XmlDocument();
            actions = new Hashtable();

            xd.Load(path);
            XsltDomSet domSet = (new XsltDomParser()).Parse(xd);

            if (Directory.Exists(outputDir))
            {
                Directory.Delete(outputDir, true);
            }
            Directory.CreateDirectory(outputDir);
            FileStream fs = new FileStream(outputDir + "\\view.html", FileMode.Create);
            StreamWriter sw = new StreamWriter(fs);


            String jsPath = outputDir + "\\action.js";
            FileStream jsfs = new FileStream(jsPath, FileMode.Create);
            StreamWriter jssw = new StreamWriter(jsfs);

            ArrayList templates = domSet.GetAllTemplates();
            for (int i = 0; i < templates.Count;i++ )
            {
                XsltTemplate value = (XsltTemplate)templates[i];
                XsltActionMap action = value.GetActionMap(data);
                String htmlText = value.ToHtml(data);
                sw.Write(htmlText);

                ArrayList list = action.GetConditionFunJs();
                for (int index = 0; index < list.Count; index++)
                {
                    String js = (String)list[index];
                    jssw.Write(js);
                }
                list = action.GetEvalFunJs();
                for (int index = 0; index < list.Count; index++)
                {
                    String js = (String)list[index];
                    jssw.Write(js);
                }
                list = action.GetOnChangeFunJs();
                for (int index = 0; index < list.Count; index++)
                {
                    String js = (String)list[index];
                    jssw.Write(js);
                }
            }
            sw.Close();
            fs.Close();

            jssw.Close();
            jsfs.Close();

            return true;
        }
    }
}
